package com.hfh.server.rabbitmq.SendMessage;

import com.alibaba.fastjson.JSONObject;
import com.hfh.server.common.CustomException;
import com.hfh.server.common.CustomHttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @author liuxinghong
 * @Description: 向消息中间件发送消息
 * @date 2019/8/28 002810:28
 */
@Service
@Slf4j
public class SendRabbitMessageImpl implements SendRabbitMessageService {

    @Value("${rabbitmq.printer-exchange-name}")
    private String printerExchangeName;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 向打印机队列发送消息
     * @param message 消息内容
     * @param routingKey 农家乐主键id
     */
    @Override
    public  void sendPrinterMessage(Object message,String routingKey){
        if (Objects.isNull(message)){
            throw new CustomException(CustomHttpStatus.PARAM_FAIL.value(),"消息内容为空，发送失败！");
        }
        if (StringUtils.isEmpty(routingKey)){
            throw new CustomException(CustomHttpStatus.PARAM_FAIL.value(),"发送的队列id为空，发送失败！");
        }
        Message mqMessage = new Message(String.valueOf(message).getBytes(),new MessageProperties());
        mqMessage.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT); //消息持久化
        mqMessage.getMessageProperties().setExpiration("2592000000");//消息在队列里存活时间(毫秒)(30天)
        try {
            rabbitTemplate.convertAndSend(printerExchangeName,routingKey,mqMessage);
            log.info("200 >>>>>消息发送成功，消息路由key： "+routingKey+" 消息内容： "+ JSONObject.toJSONString(message));
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

}
